package com.gec.mall.security.config;

import com.gec.mall.security.component.RestAuthenticationEntryPoin;
import com.gec.mall.security.component.RestAuthorizationHandler;
import com.gec.mall.security.filter.JwtAuthorizationFilter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Author: li
 * @Date: 2023/2/17
 * @PACKAGE_NAME:com.gec.security.config
 * @Project_Name:Javademo
 * @VERSION: 1.0.0
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()    //表示CrossOrigin解决跨域问题
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)     //无状态认证
                .and()
                .authorizeRequests()
                .antMatchers("/doLogin","/mall-content/*/*","/mall-elasticsearch/EsItem/*","/mall-elasticsearch/EsItem/*/*")
                .permitAll()    //doLogin资源不被拦截
                .anyRequest()
                .authenticated()    //除了前面的资源，其他都要认证
                .and()
                //.addFilterBefore(new JwtAuthenticationFilter("/doLogin", authenticationManager()), UsernamePasswordAuthenticationFilter.class);     //添加用户认证过程的过滤器（用户登录）
                .addFilterBefore(new JwtAuthorizationFilter(),UsernamePasswordAuthenticationFilter.class);    //资源的拦截认证过滤器，判断jwt的有效性

        http.csrf().disable();

        //报错的处理组件
        http.exceptionHandling().accessDeniedHandler(new RestAuthorizationHandler())
                                .authenticationEntryPoint(new RestAuthenticationEntryPoin());



    }
}
